package com.shycloud.mido.organ.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.pay.wxpay.WXPay;
import com.shycloud.mido.common.pay.wxpay.utils.PayCommonUtil;
import com.shycloud.mido.common.pay.wxpay.utils.WxConfigUtil;
import com.shycloud.mido.organ.api.entity.LiveRoomEntity;
import com.shycloud.mido.organ.api.entity.RecordRoomEntity;
import com.shycloud.mido.organ.mapper.LiveRoomMapper;
import com.shycloud.mido.organ.mapper.RecordRoomMapper;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.lang.StringUtils;
import org.jdom.JDOMException;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.AllArgsConstructor;

@RestController
@AllArgsConstructor
@RequestMapping("/record")
public class RecordRoomController {

	/** 七牛云上传 */
	private MinioTemplate minioTemplate;
	private RecordRoomMapper recordRoomMapper;
	private LiveRoomMapper liveRoomMapper;

	//后台用接口

	//上传文件
	public String uploadFile(MultipartFile file) {

		//文件上传路径
		String url = StringUtils.EMPTY;

		if (!StringUtils.EMPTY.equals(file.getOriginalFilename())) {

			//提取文件名
			String fileName = file.getOriginalFilename().replaceAll(" ", "");
			//后缀
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			String uuid = UUID.randomUUID().toString();
			//提取上传文件名称
			String uploadFileName = uuid.replace("-", "") + "." + suffix;

			try {
				//上传课件
				minioTemplate.uploadFile(file.getInputStream(), uploadFileName, "zebra-courseware");
			} catch (IOException e) {
				throw new BusinessException(e.getLocalizedMessage());
			}

			url = "http://vediorecording.joymido.com/" + uploadFileName;
		}
		return url;
	}

	@Transactional
	@PostMapping("/addRoom")
	public R addRoom(@RequestBody RecordRoomEntity room) {
		//新增匿名直播间
		// LiveRoomEntity liveRoom = new LiveRoomEntity();
		// liveRoom.setIsAnonymous("1");
		// liveRoomMapper.insert(liveRoom);
		// room.setLiveroomId(liveRoom.getId());
		//如果已经绑定过直播间id则不能插入
//		QueryWrapper queryWrapper = new QueryWrapper<>();
//		queryWrapper.eq("liveroom_id", room.getLiveroomId());
//		if (recordRoomMapper.selectList(queryWrapper).size() > 0) {
//			throw new BusinessException("此直播间已关联过录播间, 请更换直播间重试！");
//		}
		room.setCreateTime(LocalDateTime.now());
		return new R<>(recordRoomMapper.insert(room));
	}

	
	@PostMapping("/updateShowAttachment")
	public R updateShowAttachment(@RequestBody RecordRoomEntity room) {
		return new R<>(recordRoomMapper.updateById(room));
	}

	@GetMapping("/deleteRoom")
	public R deleteRoom(String roomId) {
		return new R<>(recordRoomMapper.deleteById(roomId));
	}

	@GetMapping("/getRoomPageAdmin")
	public R getRoomPageAdmin(Page<RecordRoomEntity> page, String name, String type) {
		QueryWrapper queryWrapper = new QueryWrapper<>();
		if (StringUtils.isNotBlank(name)) {
			queryWrapper.like("name", name);
		}
		if (StringUtils.isNotBlank(type)) {
			queryWrapper.eq("type", type);
		}
		queryWrapper.orderByDesc("create_time");
		return new R<>(recordRoomMapper.selectPage(page, queryWrapper));
	}

	@GetMapping("/getUploadToken")
	public R getUploadToken() {
		Map<String, Object> resultMap = new HashMap<>();
		//long overTime = 3600;
		resultMap.put("token", minioTemplate.getPrivateUploadToken("mido-video-recording", null));
		resultMap.put("overTime", 3600);
		return new R(resultMap);
	}

	//下面是微信分账测试逻辑
	@GetMapping("/addReceiver")
	public R addReceiver() {
		SortedMap<Object, Object> parameters = new TreeMap<>();
		parameters.put("mch_id", WxConfigUtil.MCH_ID);
		parameters.put("appid", WxConfigUtil.APPID);
		parameters.put("nonce_str", PayCommonUtil.createNoncestr());
		//添加分账接收方对象
		Map<String, Object> receiverMap = new LinkedHashMap<String, Object>();
		receiverMap.put("type", "PERSONAL_OPENID");
		//此处输入绑定账户的openId
		receiverMap.put("account", "o7d6Ms-WcUquOxpk9zX0oAreoKmY");
		receiverMap.put("relation_type", "USER");
		parameters.put("receiver", JSON.toJSONString(receiverMap));
		return new R(PayCommonUtil.wxRequest(WxConfigUtil.ADD_RECEIVER_URL, "POST", WxConfigUtil.SHA256, parameters));
	}

	@GetMapping("/unifiedorder")
	public R unifiedorder(String orderId) {
		SortedMap<Object, Object> parameters = new TreeMap<>();
		parameters.put("mch_id", WxConfigUtil.MCH_ID);
		parameters.put("appid", WxConfigUtil.APPID);
		parameters.put("nonce_str", PayCommonUtil.createNoncestr());
		parameters.put("body", "快乐斑马-套餐购买");
		parameters.put("out_trade_no", orderId);
		parameters.put("total_fee", "2");
		parameters.put("spbill_create_ip", PayCommonUtil.getIPAddress());
		parameters.put("notify_url", WxConfigUtil.WX_NOTIFY_URL_TEST);
		parameters.put("trade_type", "MWEB");
		//场景信息
		Map<String, Object> sceneMap = new LinkedHashMap<String, Object>();
		Map<String, Object> h5Info = new LinkedHashMap<String, Object>();
		h5Info.put("type", "Wap");
		h5Info.put("wap_url", "http://shop.joymido.com/");
		h5Info.put("wap_name", "扫码支付");
		sceneMap.put("h5_info", h5Info);
		parameters.put("scene_info", JSON.toJSONString(sceneMap));
		return new R(PayCommonUtil.wxRequest(WxConfigUtil.UNIFIED_ORDER_URL, "POST", WxConfigUtil.MD5, parameters));
	}

	@GetMapping("/profitsharing")
	public R profitsharing() {
		SortedMap<Object, Object> parameters = new TreeMap<>();
		parameters.put("mch_id", WxConfigUtil.MCH_ID);
		parameters.put("appid", WxConfigUtil.APPID);
		parameters.put("nonce_str", PayCommonUtil.createNoncestr());
		parameters.put("transaction_id", "4200000831202101042364271652");
		parameters.put("out_order_no", "4200000831202101042364271652");
		List<Map> receivers = new ArrayList<>();
		Map<String, Object> receiverMap = new LinkedHashMap<String, Object>();
		receiverMap.put("type", "PERSONAL_OPENID");
		//此处输入绑定账户的openId
		receiverMap.put("account", "o7d6Ms-WcUquOxpk9zX0oAreoKmY");
		receiverMap.put("relation_type", "USER");
		//先将分账方添加进列表中
		//再将列表序列化添加到SortedMap中
		receivers.add(receiverMap);
		parameters.put("receivers", JSON.toJSONString(receivers));
		return new R(PayCommonUtil.wxRequest(WxConfigUtil.PROFIT_SHARING_URL, "POST", WxConfigUtil.SHA256, parameters));
	}

	@PostMapping("/wxNotify")
	public R wxNotify(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> map = new HashMap<>();
		try {
			map = WXPay.wxNotify(request, response);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JDOMException e) {
			e.printStackTrace();
		}
		return new R(map);
	}

}
